﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tesseract;

namespace WpfApp.Models
{
    internal class OcrProcessor : IDisposable
    {
        private readonly TesseractEngine _ocrEngine;
        private static readonly string DefaultTessDataPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\..\WpfApp\testdata"));
        public OcrProcessor(string tessDataPath = null, string language = "eng")
        {
            if (tessDataPath == null)
            {
                tessDataPath ??= DefaultTessDataPath;
                Console.WriteLine("tessDataPath is null");
            }
            try
            {
                Console.WriteLine($"Initializing Tesseract with tessDataPath: {tessDataPath}");
                _ocrEngine = new TesseractEngine(tessDataPath, language);
            }
            catch (TesseractException ex)
            {
                throw new InvalidOperationException("Failed to initialize Tesseract engine", ex);
            }
        }

        public List<string> ExtractTextFromImage(string imagePath)
        {
            if (string.IsNullOrEmpty(imagePath) || !File.Exists(imagePath))
            {
                throw new FileNotFoundException("Specified image file not found");
            }

            using (var img = Pix.LoadFromFile(imagePath))
            {
                return ExtractTextFromImage(img);
            }
        }

        public List<string> ExtractTextFromImage(Pix image)
        {
            var words = new List<string>();

            try
            {
                using (var page = _ocrEngine.Process(image))
                {
                    var text = page.GetText();
                    words.AddRange(text.Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error during OCR processing: {ex.Message}");
            }

            return words;
        }

        public void Dispose()
        {
            _ocrEngine.Dispose();
        }
    }
}
